<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<link rel="stylesheet" href="css/main.css">
	<link rel="stylesheet" href="css/class_circle_message.css">
	<title>聊天窗口</title>

</head>

<body>
	<div id="container">
		<div class="contain" id="vue-root">
			<form id="form" method="post" ref="form" enctype="multipart/form-data" style="display: none">
				<input type="file" ref="file" id="file" name="file" accept="image/*" @change="upload">
			</form>

			<div class="header">
				<div class="header_title">
					<span v-text="to.name"></span>
					<span v-text="getType(to.type)"></span>
				</div>
				<img src="image/return.png" alt="" class="return" onclick="history.back()">
			</div>
			<div id="main">
				<div class="m-message" id="body">
					<ul>
						<li v-for="chat in chats">
							<p class="time">
								<span v-text="chat.time"></span>
							</p>
							<div class="main" :class="{self:chat.self}">
								<img class="avatar" :src="(chat.self?me:to).avatar">
								<div class="text">
									<template v-if="!chat.type">{{chat.content}}</template>
									<img v-if="chat.type==1" :src="getImg(chat.content)" @click="view(chat.content)">
								</div>
							</div>
						</li>

					</ul>
				</div>

			</div>
			<div class="chatBox-send">
				<input class="div-textarea" v-model="msg" style="width: 70%">
				<label title="发送图片" class="btn-default-styles" @click="choose">
					<img src="image/picture.png">
				</label>
				<input type="button" value="发送" class="button_input" @click="send(msg)">
				<!-- <img src="/wechat/image/bia.png"> -->
			</div>
			<!-- <div style="position: fixed;bottom: 45px;right: 0;"></div> -->

		</div>
	</div>

	<script src="/scriptZIP/qs.min.js"></script>
	<script src="/scriptZIP/vue.min.js"></script>
	<script src="/scriptZIP/axios.min.js"></script>
	<script src="/scriptZIP/dayjs.min.js"></script>
	<script src="/scriptZIP/sockjs.min.js"></script>
	<script src="/scriptZIP/stomp.min.js"></script>



	<script src="/wechat/js/wx.js"></script>
	<script src="/js/common.js"></script>


	<script>

		var person = {};

		if (params().user) {
			getPerson = function () {
				return person;
			}
		}

		function listen(func) {
			var client = Stomp.over(new SockJS('/ws'));
			client.debug = function (str) {
			};

			client.connect({}, function () {
				client.subscribe('/user/topic/chat', func);
			}, function (error) {
				alert('连接出错，重新连接...');
				listen(func);
			});
		}


		new Vue({
			el: '#vue-root',
			data: {
				me: {},
				to: {},
				chats: [],
				msg: null,
				isTeacher: false,
				person: {}
			},
			created: function () {
				var query = params();
				var user = query.user;
				if (user) {
					this.isTeacher = user == 'teacher';
					var url = this.isTeacher ? '/t/bound' : '/s/me';

					axios.get(url).then(function (res) {
						this.person = res.data;
						person = this.person;
						this.init();
					}.bind(this));
				} else {
					this.isTeacher = isTeacher();
					this.person = getPerson();
					this.init();
				}
			},
			methods: {
				init: function () {
					var query = params();
					var personId = query.personId;
					var type = query.type;
					this.key = 'hxt-chat-' + this.person.id + '_' + personId;
					if (this.isTeacher) {
						axios.post('/t/chat/to/' + personId + '/' + type).then(this.init0);
						this.key += '.' + type;
					} else {
						axios.post('/s/chat/to/' + personId).then(this.init0);
					}
					this.chats = this.getHistory();
				},
				init0: function (res) {
					var data = res.data;
					['me', 'to'].forEach(function (it) {
						this[it] = data[it];
						this[it].avatar = this.getAvatar(this[it]);
					}.bind(this));
					this.getMsg();
					listen(function (msg) {
						msg = msg.body;
						if (!msg) this.getMsg();
					}.bind(this));
				},
				getMsg: function () {
					axios.get(this.prefix + '/chat').then(function (res) {
						var data = res.data;
						if (data.length == 0) return;
						axios.post(this.prefix + '/chat/read', data.map(function (it) {
							return it.id;
						}));
						this.chats = this.chats.concat(data);
					}.bind(this));
				},
				getAvatar: function (person) {
					if (!person.avatar) return 'image/avatar.svg';
					return '/static/' + this.schoolId + '/' + (person.type == -1 ? 'teacher' : 'binding') + '/' + person.avatar;
				},
				getType: function (type) {
					if (type == -1) return '老师';
					return ['', '爸爸', '妈妈', '家长'][type];
				},
				send: function (content, type) {
					if (!content) return;
					var o = { content: content, type: type };
					axios.post(this.prefix + '/chat', o).then(function (res) {
						this.chats.push(Object.assign({
							self: true,
							time: dayjs().format('YYYY-MM-DD HH:mm:ss')
						}, o));
						if (!type) this.msg = null;
					}.bind(this));
				},
				getImg: function (pic) {
					return '/static/' + this.schoolId + '/chat/' + pic;
				},
				view: function (pic) {
					wxPreviewImg([this.getImg(pic)], 0);
				},
				choose: function () {
					if (wxReady) {
						wxChooseImg(9, 'chat', this.sendImg);
					} else {
						this.$refs.file.click();
					}
				},
				upload: function () {
					axios.post(this.prefix + '/upload/chat?schoolId=' + this.schoolId,
						new FormData(this.$refs.form)).then(function (res) {
							this.send(res.data.data, 1);
						}.bind(this));
				},
				sendImg: function (pic) {
					this.send(pic, 1);
				},
				save: function () {
					localStorage[this.key] = JSON.stringify(this.chats);
				},
				getHistory: function () {
					var chats = localStorage[this.key];
					if (!chats) return [];
					chats = JSON.parse(chats);
					chats.sort(function (a, b) {
						a = a.time;
						b = b.time;
						if (a == b) return 0;
						return a > b ? 1 : -1;
					});
					return chats;
				}
			},
			computed: {
				schoolId: function () {
					return this.person.schoolId;
				},
				prefix: function () {
					return this.isTeacher ? '/t' : '/s';
				}
			},
			watch: {
				chats: function (newValue, oldValue) {
					this.$nextTick(function () {
						var a = document.getElementById('body');
						a.scrollTop = a.scrollHeight;
					});
					this.save(newValue);
				}
			}
		});

	</script>

</body>

</html>